import pyodbc


def get_db_connection():
    SERVER = '172.16.17.152'
    USER = 'sa'
    PASSWORD = 'sl54321'
    DATABASE = 'jackyunerp'

    try:
        connection = pyodbc.connect(
            f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={SERVER};DATABASE={DATABASE};UID={USER};PWD={PASSWORD}'
        )
        return connection
    except Exception as e:
        print(f"Error connecting to the database: {e}")
        return None


def db1_execute_query(sql):
    connection = get_db_connection()
    if connection:
        try:
            cursor = connection.cursor()
            cursor.execute(sql)
            columns = [column[0] for column in cursor.description]
            results = [dict(zip(columns, row)) for row in cursor.fetchall()]
            connection.close()
            return results
        except Exception as e:
            print(f"Error executing query: {e}")
            return None
    else:
        return None


# 示例使用
# sql = "SELECT * FROM word_to_json_dic"
# results = db1_execute_query(sql)
# if results:
#     for row in results:
#         print(row)
